const fs = require('fs')
const path = require('path')
const glob = require('glob')
const { resolve, isPc ,isDiy} = require('./utils')

const widgetTpl = `<template>
  <view><!-- widgets -->
  </view>
</template>

<script>
export default {
  name: 'widget-item',
  props: {
    widget: {},
    model: {}
  },
  methods: {
  }
}
</script>
`

function getComponents(type) {
  const regDir = resolve('src', type)

  if (!fs.existsSync(regDir)) {
    return []
  }

  const files = glob.sync(`${regDir}/**/index.vue`)

  return files.map(file => {
    const componentPath = path.relative(regDir, file)
      .replace(/\\/g, '/')
      .replace('/index.vue', '')
    const componentName = componentPath.replace(/^.*\//, '')
    const componentUpperName = componentName
      .replace(/-(\w)/g, (match, $1) => $1.toUpperCase())

    return {
      path: componentPath,
      name: componentName,
      upperName: componentUpperName
    }
  })
}

module.exports = async () => {
  var maxCount=1
  var totalCount=0
  if(isDiy){
    maxCount=1
  }
  console.log('开始更新组件引用')

  const tplPath = resolve('src/main.tpl.js')

  if (!fs.existsSync(tplPath)) {
    console.warn('模板文件 main.tpl.js 不存在')
    return
  }

  const typeEnum = ['components', 'elements', 'admins']
  const tplContent = fs.readFileSync(tplPath).toString()
  const mainPath = resolve('src/main.js')


  let globalComponents = ''

  typeEnum.forEach(type => {
    getComponents(type).forEach(component => {
      var count=0
      for(var i=0;i<component.path.length;i++){
        if(component.path[i]==='/'){
          count++
        }
      }
      if(count<=maxCount){
        globalComponents += `import ${component.upperName} from '@/${type}/${component.path}/index.vue'\n`
        console.info('自动构建main.js中的组件',component.path)
        totalCount++
      }

    })
  })

  typeEnum.forEach(type => {
    getComponents(type).forEach(component => {
      var count=0
      for(var i=0;i<component.path.length;i++){
        if(component.path[i]==='/'){
          count++
        }
      }
      if(count<=maxCount){
      globalComponents += `Vue.component('${component.name}', ${component.upperName})\n`
      }
    })
  })

  const mainContent = tplContent.replace('/* 5ug auto-import */', globalComponents)

  fs.writeFileSync(mainPath, mainContent)

  console.log('组件引用更新成功')

  const widgetDir = resolve('src/elements/all/x-widget')
  console.info('是否是PC',isPc,'是否DIY',isDiy)
  console.info('元件和组件总数：', totalCount)
  if (isPc || !fs.existsSync(widgetDir)) {
    return
  }

  const widgetEnum = ['components', 'admins']
  let widgetTags = ''

  widgetEnum.forEach(type => {
    getComponents(type).forEach(component => {
      widgetTags += `\n    <${component.name} :widget="widget" v-if="widget.componentPath === '/${component.path}'"></${component.name}>`
    })
  })

  const widgetContent = widgetTpl.replace('<!-- widgets -->', widgetTags)
  const widgetPath = path.join(widgetDir, 'widget-item.vue')

  fs.writeFileSync(widgetPath, widgetContent)

  console.log('widget-item 更新成功')
}
